﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PubSubLite.Configuration;

namespace PubSubLite
{
    internal class BusHelper
    {
        public BusHelper(IBus bus, IBusConfiguration config)
        {
            _bus = bus;
            _configuration = config;
        }

        private IBus _bus;
        private IBusConfiguration _configuration;

        private void HandleException(Exception ex)
        {
            _configuration.Log(ex);
            if (_configuration.RethrowExceptions)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Executes and action 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="arg1"></param>
        internal void Execute<T>(Action<T> action, T arg1)
            where T : class
        {
            try
            {
                action(arg1);
            }
            catch (Exception e)
            {
                HandleException(e);
            }
        }


        internal TResult Execute<T1, TResult>(Func<T1, TResult> func, T1 arg1)
        {
            var retVal = default(TResult);
            try
            {
                retVal = func(arg1);
            }
            catch (Exception e)
            {
                HandleException(e);
            }
            return retVal;
        }
    }
}
